<?php
namespace cms\modules\v1\models;

use common\models\Common;
use common\models\Functions;
use common\models\Status;
use common\services\upload\AliyunOSS;
use common\services\upload\Qiniu;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class Upload extends Common
{

    public function upload($check = true) {
        try {

            if (!$_FILES) {
                throw new Exception('请选择图片');
            }
            $path = Functions::uploadFile('file', '');
            if (empty($path)) {
                throw new Exception('上传内容为空');
            }
            $result = [
                'url' => $this->imageHost . $path,
                'path' => $path,
            ];
            return Functions::formatRestAPI(0, '上传成功', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function deleteImage($imageUrl = '') {
        try {
            if (empty($imageUrl)) {
                throw new Exception('未知图片');
            }

            $dWhere['image_url'] = $imageUrl;
            $res = static::deleteAll($dWhere);
            if ($res === false) {
                throw new Exception('删除失败');
            }
            //删除文件
            if (file_exists($imageUrl)) {
                @unlink($imageUrl);
            }
            return Functions::formatRestAPI(0, '删除成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public static function deleteFile($path = '') {

        $oldFileFullPath = \Yii::getAlias("@uploads") . $path;
        if (!empty($path) && file_exists($oldFileFullPath)) {
            @unlink($oldFileFullPath);
        }
    }

    public function uploadToQiniu() {
        try {
            $post = Yii::$app->request->post();
            $pre = isset($post['pre']) && !empty($post['pre']) ? $post['pre'] : 'multiple';

            $key = $post['key'] ?? 0;
            $path = (new Qiniu())->uploadFile($pre, 'file');

            $result = [
                'url' => $this->imageHost . $path,
                'path' => $path,
                'key' => $key
            ];

            return Functions::formatRestAPI(0, '上传成功', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
    public function uploadToAli() {
        try {
            $post = Yii::$app->request->post();
            $pre = isset($post['pre']) && !empty($post['pre']) ? $post['pre'] : 'app';

            $key = $post['key'] ?? 0;
            $path = (new AliyunOSS())->uploadFile($pre, 'file');

            $result = [
                'url' => $this->imageHost . $path,
                'path' => $path,
                'key' => $key
            ];

            return Functions::formatRestAPI(0, '上传成功', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * editWang 富文本编辑器上传图片 上传图片到七牛
     * @param bool $check
     * @return array
     */
    public function uploadForWang($check = true) {
        try {
            if ($check) {
                $data['user_id'] = 0;
            }

            $post = Yii::$app->request->post();

            $pre = isset($post['pre']) && !empty($post['pre']) ? $post['pre'] : 'editorWang';
            $result = [];

            if ($_FILES) {
                foreach ($_FILES as $k => $v) {
                    $path = (new Qiniu())->uploadFile($pre,$k, '');
                    if (empty($path)) {
                        throw new Exception('上传内容为空');
                    }
                    $result['data'][] = $this->imageHost . $path;
                }
            }

            return ['errno' => 0, 'data' => $result['data']];
        } catch (Exception $e) {
            return ['errno' => 1, "message" => $e->getMessage(), 'data' => null];
        }
    }
    /**
     * editWang 富文本编辑器上传图片 上传图片到七牛
     * @param bool $check
     * @return array
     */
    public function uploadForWangAli($check = true) {
        try {
            if ($check) {
                $data['user_id'] = 0;
            }

            $post = Yii::$app->request->post();

            $pre = isset($post['pre']) && !empty($post['pre']) ? $post['pre'] : 'editorWang';
            $result = [];

            if ($_FILES) {
                foreach ($_FILES as $k => $v) {
                    $path = (new AliyunOSS())->uploadFile($pre, $k, '');
                    if (empty($path)) {
                        throw new Exception('上传内容为空');
                    }
                    $result['data'][] = $this->imageHost . $path;
                }
            }

            return ['errno' => 0, 'data' => $result['data']];
        } catch (Exception $e) {
            return ['errno' => 1, "message" => $e->getMessage(), 'data' => null];
        }
    }


    /**
     * 上传视频 使用七牛云上传音视频
     * @return array|string
     */
    public function getUpToken() {
        $post = Yii::$app->request->post();
        $fileType = $post['fileType'];
        $fileName = $post['fileName'];

        $ext = strtolower(pathinfo($fileName,PATHINFO_EXTENSION));
        $key = md5(time() . rand(10000, 99999));
        $uoToken = '';

        $pre = 'video';
        $codeStatus = Status::TRANS_CODE_STATUS_DOING;
        //音频
        if (strpos($fileType,'audio') !== false) {
            if ($ext == 'mp3') {
                $codeStatus = Status::TRANS_CODE_STATUS_DONE;
            }
            $qiniuModel = new Qiniu();
            $uoToken = $qiniuModel->getUpToken($key,'mp3',$ext,$qiniuModel::TRANS_CODE_URL_LEARN);
        }

        //视频
        if (strpos($fileType,'video') !== false) {
            if ($ext == 'mp4') {
                $codeStatus = Status::TRANS_CODE_STATUS_DONE;
            }
            $qiniuModel = new Qiniu();
            $uoToken = $qiniuModel->getUpToken($key,'mp4',$ext,$qiniuModel::TRANS_CODE_URL_LEARN);
        }
        return [
            'upToken' => $uoToken,
            'key' => $pre.'/'.$key .'.'. $ext,
            'codeStatus' => $codeStatus,
        ];
    }
}
